import { createFetch } from "@vueuse/core";
import { ElNotification } from "element-plus";

import setting from "./setting";
import appToken from "./appToken";
import router from "@/router";

const toLogin = () => {
  const query = `${location.pathname}${location.search}`;
  router.replace(`/login?from=${encodeURIComponent(query)}`);
};

const useMyFetch = createFetch({
  baseUrl: setting.requestHost + setting.requestPath,
  options: {
    updateDataOnError: true,
    async beforeFetch({ options = {} }) {
      const token = appToken.getToken();

      if (!options.headers) {
        options.headers = {};
      }

      // token 存在
      if (token) {
        Reflect.set(options.headers, "Authorization", `Bearer ${token}`);
      }

      return { options };
    },

    // 在请求后处理数据，如：拦截错误、处理过期
    afterFetch({ data, response }) {
      if (typeof data == "string") {
        console.warn("结果为字符串", data);
      }

      if (data.code == "0") {
        return { data: data.data, response };
      }

      return Promise.reject({ msg: data.msg });
    },

    // 请求错误,包括会捕捉 onFetchResponse 里面的异常
    onFetchError({ data, error, response }) {
      console.log("onFetchError", "data", data);
      console.error("请求失败，原因", error);
      console.error("请求失败，响应内容", response);

      if (response?.status == 401) {
        ElNotification({ title: "请登录" });
        toLogin();
      } else {
        ElNotification({
          type: "error",
          title: error.msg || "请求失败",
          message: error.msg ? "请求失败" : "",
        });
      }

      return { data: {}, error, response };
    },
  },
});

export default useMyFetch;
